use std::collections::HashMap;

use crate::*;
use anyhow::bail;
use common::RegexResult;
use http::request::Parts;
use http::HeaderMap;
use leptos::logging;
use leptos::*;
use serde::{Deserialize, Serialize};

/**
* 文本文件的grep搜索,
* 这是一个典型的调用异步API，返回结构化数据的案例：
- 目前采用reqwest执行REST请求；
- URI基于 window().location().host()获取；也可以web_sys::js_sys::eval("window.location.host");

*/
#[component]
pub fn SearchPage() -> impl IntoView {
    let search_result_t: HashMap<String, Vec<RegexResult>> = HashMap::new();
    let (sresult, set_sresult) = create_signal(search_result_t);
    let (keyword, set_keyword) = create_signal(String::new());

    view! {
        <div align="center">
        <p><a href="https://docs.rs/regex/latest/regex/#syntax">"regex syntax"</a> </p>
      <input type="text" size="50" placeholder="input your question!" id="inputbox" on:input=move |ev| set_keyword.set(event_target_value(&ev)) />

      <button style="margin:10px" on:click=move |_| {
        let keyword_val = keyword.get();        

        if let Some(chatview) = document().get_element_by_id("waitingview"){
          chatview.set_inner_html("<div>  <p class=\"wait-tips\">Waiting ... ...!</p> </div>");
        }else{
          logging::log!("can't get element by waitingview");
        }

        spawn_local(async move {            
            if let Ok(r) = get_my_grep_search(&keyword_val).await {
              if r.len() > 0 {
                set_sresult.set(r);
              }
            }
            if let Some(chatview) = document().get_element_by_id("waitingview"){
              chatview.set_inner_html("<br/>");
            }else{
              logging::log!("can't get element by waitingview");
            }           
            
          });

      }>提问</button>
    </div>
    <div id="waitingview"> </div>
    <div id="hello" align="left">
    <Transition  >
         {
            move || {
                let items = sresult.get();
                items.into_iter().enumerate().map(|(no,item)| {
                    view! {
                        <div>{no+1}. {item.0}</div>
                        <div>
                        {  item.1.iter().map(|s| {
                            let line = s.line_no;
                            view! {
                              <li>"[ line : " {line} " ] " {s.line_prefix.clone()}<mark>{s.mit_word.clone()}</mark>{s.line_end.clone()}</li>
                            }
                            }).collect_view()
                        }
                        </div><br/>
                    }
                })
                .collect_view()
            }
        }
    </Transition>
    <Suspense>
    {
        move || {
          let items = sresult.get();
          if items.len() > 0 {
            view! {
              <div align="center">" --- END --- "</div>
            } 
          }else {
            view! {
              <div align="center">" --- NO RESULT --- "</div>
            } 
          }
        }
    } 
    </Suspense>
    </div>
        }
}

async fn get_my_grep_search(query: &str) -> Result<HashMap<String, Vec<RegexResult>>> {
    let host = window().location().host().unwrap();
    // let r = web_sys::js_sys::eval("window.location.host");
    let api = format!("http://{}/api/grep_search?query={}", host, query);
    logging::log!("api = {:#?}", api);
    let client = reqwest::Client::new();
    let mut headers = HeaderMap::new();
    headers.insert("Authorization", "Bearer abc".parse()?);
    headers.insert("Content-Type", "application/json; charset=utf-8".parse()?);

    let r: HashMap<String, Vec<RegexResult>> = client
        .get(&api)
        .headers(headers)
        .send()
        .await?
        .json()
        .await?;

    logging::log!("get_axum_data, count =  {}", r.len());
    return std::result::Result::Ok(r);
}
